import axios from 'axios'
import { ElNotification } from 'element-plus'
import useUserStore from '../store/modules/user'
import { API_URL } from '../config/app'

const userStore = useUserStore()

const service = axios.create({ baseURL: API_URL, timeout: 30 * 1000 })

service.interceptors.request.use(
  config => {
    const token = userStore.token
    if (token) config.headers.Authorization = token

    return config
  },
  error => {
    console.log('request interceptors error: ', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const result = response.data

    // 响应是文件类型
    if (!response.headers['content-type'].includes('application/json')) return response

    if (result.status === 'OK') return result.data

    const { hideNotify } = response.config
    if (!hideNotify) ElNotification.error({ message: result.message || '未知错误' })

    return Promise.reject(result)
  },
  error => {
    console.log('response interceptors error: ', error)
    return Promise.reject(error)
  }
)

export default service
